/*
 * CopyLeft (c) 2001->infinity by Michael U. Bergens for starters.
 *
 *   Long story short: Apache 2.0, no warranty whatsoever, no obligations
 *   of any kind on the part of the authors nor on the part of the consumers of this code.
 */
package org.michael.u.brg.by.sys;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**Asynchronous IO Stream consumer.
 * 
 * @see #IoStreamConsumer(java.io.InputStream)
 * @see #run()
 * @see #consume(String)
 * @see #recordException(Exception)
 * @author Michael Bergens
 */
public abstract class IoStreamConsumer extends Thread {

    private final InputStream inputStream;

    /**
     * Constructor with the stream.
     * @param inputStream the stream to consume the content from.
     * @see #consume(String) 
     */
    protected IoStreamConsumer(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    /**
     * The read loop, runs asynchronously in the thread till the stream runs out of lines.
     */
    @Override public void run() {
        final InputStreamReader reader = new InputStreamReader(inputStream);
        final BufferedReader bufferedReader = new BufferedReader(reader);
        String line;
        try {
            while((line = bufferedReader.readLine()) != null) {
                consume(line);
            }
        }
        catch (IOException e) {
            recordException(e);
        }
    }

    /**
     * This implementation of this method will be called with every line that becomes available
     * from the stream passed to the constructor.
     * @param content the argument will have the next line from the stream.
     */
    public abstract void consume(String content);

    /**
     * This implementation of this method will be called with every {@link Exception} thrown during the execution
     * of the {@link #run()} method.
     * @param exception the argument will have the exception that was thrown if any.
     */
    public abstract void recordException(Exception exception);

}
